use  case bari_num using "${Input}\mhd1_dta\mhdcvr1.dta"  
save ${Output}\BariInfo, replace
generate str1 junk=substr(case,1,1)
generate str6 num=substr(case,2,6)
encode num, gen(num2)
drop num
generate num=1000000 if junk=="E"
replace num=5000000 if junk=="I"
generate NewCase=num+num2
drop num num2 junk 

generate str1 junk=substr(bari_num,1,1)
generate str6 num=substr(bari_num,2,6)
encode num, gen(num2)
drop num
generate num=1000000 if junk=="E"
replace num=5000000 if junk=="I"
generate NewBariNum=num+num2
drop num num2 junk 


generate str1 junk=substr(case,1,1)
generate str6 num=substr(case,1,3)
generate str6 vilid=substr(case,1,3)
encode num, gen(num2)
drop num
generate num=1000 if junk=="E"
replace num=5000 if junk=="I"
generate NewVilid=num+num2
drop num num2 junk 

sort NewBariNum
by NewBariNum: generate NewPerson=_n 
sort case
save ${Output}\BariInfo, replace

use ${Output}\MainFile
sort case
merge case using ${Output}\BariInfo,nokeep
drop _merge
save ${Output}\MainFile, replace
